# x varname
# vx varnames to check against for uniqueness
cphsoc_varname_truncate <- function(x,vx,len=32)
{
  # truncate string to legal length
  xout <- substr(x,1,len)
  #trim traling space and underscore
  xout <- gsub('"',"'",gsub('\\s+$|_*$|^\\s+','',xout))
  # first macth on the truncated string, if not unique go on
  if(is.na(match(xout,vx))) return(xout)
  # truncate by two and add numbers up to 99
  xtmp0 <- xout
  xtmp <- substr(xtmp0,1,nchar(xtmp0)-2)
  for(i in 0:9)
  {
    xout <- paste(xtmp,0,i,sep='')
    if(is.na(match(xout,vx))) return(xout)
  }
  # continue up to 99
  for(i in 10:99)
  {
    xout <- paste(xtmp,i,sep='')
    if(is.na(match(xout,vx))) return(xout)
  }
  #if not enough continue up to 9999
  xtmp <- substr(xtmp0,1,nchar(xtmp0)-4)
  for(i in 100:999)
  {
    xout <- paste(xtmp,0,i,sep='')
    if(is.na(match(xout,vx))) return(xout)
  }
  for(i in 1000:9999)
  {
    xout <- paste(xtmp,i,sep='')
    if(is.na(match(xout,vx))) return(xout)
  }
  # if unsuccessful return NA
  NA
}
